#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "err.hpp"

class Sock
{
    const static int backlog = 32;

public:
    Sock() : _lisentsock(-1)
    {
    }
    ~Sock()
    {
        if(_lisentsock > 0) close(_lisentsock);
    }
    int Socket()
    {
        // 1. 创建socket文件套接字对象
        _lisentsock = socket(AF_INET, SOCK_STREAM, 0);
        if (_lisentsock < 0)
        {
            logMessage(FATAL, "create socket error");
            exit(SOCKET_ERR);
        }
        logMessage(NORMAL, "create socket success: %d", _lisentsock);

        //设置地址服用, 方便服务器立即重启
        int opt = 1;
        setsockopt(_lisentsock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));
    }

    void Bind(int port)
    {
        // 2. bind绑定自己的网络信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;
        if (bind(_lisentsock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind socket error");
            exit(BIND_ERR);
        }
        logMessage(NORMAL, "bind socket success");
    }

    void Listen()
    {
        // 3. 设置socket 为监听状态
        if (listen(_lisentsock, backlog) < 0) // 第二个参数backlog后面在填这个坑
        {
            logMessage(FATAL, "listen socket error");
            exit(LISTEN_ERR);
        }
        logMessage(NORMAL, "listen socket success");
    }

    int Accept(std::string *clientip, uint16_t *clientport, int* err)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sock = accept(_lisentsock, (struct sockaddr *)&peer, &len);
        logMessage(DEBUG, "accept sock: %d", sock);
        *err = errno;
        if (sock < 0)
            logMessage(ERROR, "accept, next");
        else
        {
            logMessage(NORMAL, "accept a new link success, get new sock: %d", sock); // ?
            *clientip = inet_ntoa(peer.sin_addr);
            *clientport = ntohs(peer.sin_port);
        }

        return sock;
    }

    int Fd()
    {
        return _lisentsock;
    }

private:
    int _lisentsock;
};